package com.example.onenet.utils;

import com.alibaba.fastjson.JSON;
import com.example.onenet.model.GeoLocationItem;
import com.example.onenet.model.OneNETStudioBase;
import com.github.cm.heclouds.onenet.studio.api.IotClient;
import com.github.cm.heclouds.onenet.studio.api.IotProfile;
import com.github.cm.heclouds.onenet.studio.api.auth.SignatureMethod;
import com.github.cm.heclouds.onenet.studio.api.entity.application.device.DeviceProperty;
import com.github.cm.heclouds.onenet.studio.api.entity.application.device.QueryDevicePropertyRequest;
import com.github.cm.heclouds.onenet.studio.api.exception.IotServerException;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

public class getOneNETDataUtil {

    private static final String userId = "178887";
    private static final String accessKey = "yLDimMit0nFMeOMY/biZm090DiMuzu0U5ZrNw0U2oeKScrhQsMpUXpvdlKE3H3SHrx3qHrkZ4UW/iF6Y5pIc7Q==";
    private static final String projectId = "B7DWYC";
    private static final String productId = "1e4CMa3IrE";
    private static final String deviceName = "smart_packages";

    private static IotClient client;


    public static void createClient() {
        IotProfile profile = new IotProfile();
        profile.userId(userId)
                .accessKey(accessKey)
                .signatureMethod(SignatureMethod.SHA256);
        client = IotClient.create(profile);
    }


    public static void getDeviceProperty(ArrayList<OneNETStudioBase> devicePropertyList){
        final String[] a = new String[4];
        try {

            CountDownLatch latch = new CountDownLatch(1);
            QueryDevicePropertyRequest request = new QueryDevicePropertyRequest();
            request.setProjectId(projectId);
            request.setProductId(productId);
            request.setDeviceName(deviceName);

            client.sendRequestAsync(request).whenComplete((response, cause) -> {
                if (response != null) {
                    System.out.println("requestId:" + response.getRequestId());
                    Gson gson = new Gson();
                    for (DeviceProperty deviceProperty : response) {
                        devicePropertyList.add(gson.fromJson(JSON.toJSONString(deviceProperty), OneNETStudioBase.class));
                    }
                } else {
                    if (cause instanceof IotServerException) {
                        IotServerException serverError = (IotServerException) cause;
                        System.err.println(serverError.getCode());
                    }
                    cause.printStackTrace();
                }
                latch.countDown();
            });
            latch.await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
